const db = require('../config/database');
const logger = require('../utils/logger');

/**
 * 系统配置控制器
 * 从数据库 system_config 表读取配置
 */
class ConfigController {
  /**
   * 获取所有系统配置（前台+后台）
   * GET /api/config
   */
  async getConfig(req, res) {
    try {
      const [configs] = await db.query('SELECT * FROM system_config');

      // 转换为对象格式 { config_key: config_value }
      const configObj = {};
      configs.forEach(item => {
        // 根据类型转换值
        let value = item.config_value;
        if (item.config_type === 'boolean') {
          value = value === '1' || value === 'true' || value === true;
        } else if (item.config_type === 'number') {
          value = parseFloat(value);
        } else if (item.config_type === 'json') {
          try {
            value = JSON.parse(value);
          } catch (e) {
            value = item.config_value;
          }
        }
        configObj[item.config_key] = value;
      });

      res.json({
        success: true,
        data: configObj
      });
    } catch (error) {
      logger.error('获取系统配置失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取单个配置
   * GET /api/config/:key
   */
  async getConfigByKey(req, res) {
    try {
      const { key } = req.params;

      const [configs] = await db.query(
        'SELECT * FROM system_config WHERE config_key = ?',
        [key]
      );

      if (configs.length === 0) {
        return res.json({ success: false, message: '配置不存在' });
      }

      const item = configs[0];
      let value = item.config_value;

      // 根据类型转换值
      if (item.config_type === 'boolean') {
        value = value === '1' || value === 'true' || value === true;
      } else if (item.config_type === 'number') {
        value = parseFloat(value);
      } else if (item.config_type === 'json') {
        try {
          value = JSON.parse(value);
        } catch (e) {
          value = item.config_value;
        }
      }

      res.json({
        success: true,
        data: {
          key: item.config_key,
          value: value,
          type: item.config_type,
          description: item.description
        }
      });
    } catch (error) {
      logger.error('获取配置失败', { error: error.message, key: req.params.key });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 更新配置（后台管理）
   * PUT /api/admin/config/:key
   */
  async updateConfig(req, res) {
    try {
      const { key } = req.params;
      const { value } = req.body;

      if (value === undefined) {
        return res.json({ success: false, message: '配置值不能为空' });
      }

      // 检查配置是否存在
      const [configs] = await db.query(
        'SELECT * FROM system_config WHERE config_key = ?',
        [key]
      );

      if (configs.length === 0) {
        return res.json({ success: false, message: '配置不存在' });
      }

      const config = configs[0];
      let configValue = value;

      // 根据类型转换值为字符串存储
      if (config.config_type === 'boolean') {
        configValue = value ? '1' : '0';
      } else if (config.config_type === 'json') {
        configValue = typeof value === 'string' ? value : JSON.stringify(value);
      } else {
        configValue = String(value);
      }

      const [result] = await db.query(
        'UPDATE system_config SET config_value = ? WHERE config_key = ?',
        [configValue, key]
      );

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '更新失败' });
      }

      logger.success('更新系统配置成功', { key, value });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新配置失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 批量更新配置（后台管理）
   * POST /api/admin/config/batch
   */
  async batchUpdateConfig(req, res) {
    try {
      const { configs } = req.body;

      if (!Array.isArray(configs) || configs.length === 0) {
        return res.json({ success: false, message: '配置列表不能为空' });
      }

      const connection = await db.getConnection();
      await connection.beginTransaction();

      try {
        for (const item of configs) {
          const { key, value } = item;
          if (!key || value === undefined) continue;

          // 查询配置类型
          const [configRows] = await connection.query(
            'SELECT config_type FROM system_config WHERE config_key = ?',
            [key]
          );

          if (configRows.length === 0) continue;

          const configType = configRows[0].config_type;
          let configValue = value;

          // 类型转换
          if (configType === 'boolean') {
            configValue = value ? '1' : '0';
          } else if (configType === 'json') {
            configValue = typeof value === 'string' ? value : JSON.stringify(value);
          } else {
            configValue = String(value);
          }

          await connection.query(
            'UPDATE system_config SET config_value = ? WHERE config_key = ?',
            [configValue, key]
          );
        }

        await connection.commit();

        logger.success('批量更新系统配置成功', { count: configs.length });

        res.json({
          success: true,
          message: '批量更新成功'
        });
      } catch (error) {
        await connection.rollback();
        throw error;
      } finally {
        connection.release();
      }
    } catch (error) {
      logger.error('批量更新配置失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取客服信息（前台）
   * GET /api/config/customer-service
   */
  async getCustomerServiceConfig(req, res) {
    try {
      const [configs] = await db.query(
        "SELECT * FROM system_config WHERE config_key LIKE 'customer_service_%'"
      );

      const serviceInfo = {};
      configs.forEach(item => {
        const key = item.config_key.replace('customer_service_', '');
        serviceInfo[key] = item.config_value;
      });

      res.json({
        success: true,
        data: serviceInfo
      });
    } catch (error) {
      logger.error('获取客服配置失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new ConfigController();

